package cn.itsource.product.service.impl;

import cn.itsource.dto.ProductDto;
import cn.itsource.product.domain.TProduct;
import cn.itsource.product.domain.TProductDetail;
import cn.itsource.product.mapper.ProductDetailMapper;
import cn.itsource.product.mapper.ProductMapper;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Override
    public PageList<TProduct> findPageByParam(ProductQuery query) {
        Example example = new Example(TProduct.class);
        //1. 拼接查询条件
        if (StringUtils.isNotBlank(query.getName())) {
            example.and().andLike("name", "%" + query.getName() + "%");
        }
        if (query.getState() != null) {
            example.and().andEqualTo("state", query.getState());
        }
        if (query.getDateParam() != null && query.getDateParam().length > 0) {
            //时间区间的查询
            example.and().andGreaterThanOrEqualTo("createtime", query.getDateParam()[0])
                    .andLessThanOrEqualTo("createtime", query.getDateParam()[1]);
        }
        example.orderBy("createtime").desc();
        //2. 分页查询
        //先添加上分页条件
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        //如果在tkmapper进行分页查询，那么务必要将查询的结果，直接new出一个PageInfo对象（否则：返回的结果，将不会有总条数）
        PageInfo<TProduct> pageInfo = new PageInfo<>(productMapper.selectByExample(example));

        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public AjaxResult saveOrUpdate(ProductDto dto) {
        if (dto.getProduct().getId() == null) {//product中的主键为空，则说明就是添加操作
            //执行添加操作前，先进行默认值赋值
            dto.getProduct().setState(TProduct.STATE_XIAJIA);
            dto.getProduct().setCreatetime(new Date());
            productMapper.insert(dto.getProduct());//执行完insert操作后，需要获取 product的自增长主键ID
            //保存服务的详情信息
            dto.getProductDetail().setProductId(dto.getProduct().getId());
            productDetailMapper.insert(dto.getProductDetail());
        } else {//否则，就是修改操作
            productMapper.updateByPrimaryKeySelective(dto.getProduct());
            productDetailMapper.updateByPrimaryKeySelective(dto.getProductDetail());
        }

        return AjaxResult.me();
    }

    @Override
    public ProductDto findDtoById(Long id) {
        //1.根据id主键查询t_product表
        TProduct product = productMapper.selectByPrimaryKey(id);
        //2. 根据id主键查询t_product_detail表，条件与字段product_id对应
        TProductDetail productDetail = productDetailMapper.findDetailByProductId(id);

        ProductDto dto = new ProductDto();
        dto.setProduct(product);
        dto.setProductDetail(productDetail);
        return dto;
    }

    @Override
    public AjaxResult updateState(String ids, Long state) {
        if (StringUtils.isBlank(ids) || state == null) {
            return AjaxResult.error().setMessage("缺少必传参数");
        }
        for (String id : StringUtils.split(ids, ",")) {
            TProduct product = new TProduct();
            product.setId(Long.parseLong(id));
            product.setState(state);
            if (state.longValue() == 0) {//下架
                product.setOffsaletime(new Date());
            } else {//上架
                product.setOnsaletime(new Date());
            }
            productMapper.updateByPrimaryKeySelective(product);
        }

        return AjaxResult.me();
    }
}
